package com.sm.service;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sm.ali.alipay.AliPay;
import com.sm.dao.GoodsMapper;
import com.sm.dao.HappyOrderMapper;
import com.sm.dao.OrderMapper;
import com.sm.dao.UserActivitiesMapper;
import com.sm.dao.VipActivitiesOrderMapper;
import com.sm.model.Goods;
import com.sm.model.Order;
import com.sm.model.ShopCar;
import com.sm.model.VipActivitiesOrder;
import com.sm.util.CommonUtil;
import com.sm.util.PageBean;
import com.sm.util.PageResult;
import com.sm.vo.OrderVO;
import com.sm.wx.vo.AjaxResult;
import com.sm.wx.vo.WxOrderVO;
import com.sm.wx.wxpay.WxPay;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ShopCarService shopCarService;

    @Autowired
    private WxPay wxPay;

    @Autowired
    private AliPay aliPay;

    @Autowired
    private HappyOrderMapper happyOrderMapper;

    public PageResult selectOrderByOrderStatus(Integer userId, Integer orderStatus, PageBean pageBean) {
        PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());
        Page<Order> orderList = orderMapper.selectOrderByOrderStatus(userId, orderStatus);
        return new PageResult(orderList.getTotal(),orderList.getResult());
    }

    public Order selectByPrimaryKey(Integer orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }

    public int updateByPrimaryKeySelective(Order record) {
        return orderMapper.updateByPrimaryKeySelective(record);
    }

    public int deleteByPrimaryKey(Integer orderId) {
        return orderMapper.deleteByPrimaryKey(orderId);
    }

    /**
     * 重新下单
     */
    @Transactional
    public AjaxResult againCreateOrder(HttpServletRequest request, OrderVO orderVO) {
        Order order = orderMapper.selectByPrimaryKey(orderVO.getOrderId());
        //微信支付
        if (orderVO.getPayType() == 2) {
            WxOrderVO wxOrderVO = new WxOrderVO("圆梦超市订单", "1", order.getOrderOn(), BigDecimal.valueOf(order.getRealTotalMoney()).multiply(new BigDecimal("100")).intValue()+"", "superMarketAgainNotify.do");
            return wxPay.appPay(request, wxOrderVO);
        }else if (orderVO.getPayType() == 1) {
            WxOrderVO wxOrderVO = new WxOrderVO("圆梦超市订单", "1", order.getOrderOn(), BigDecimal.valueOf(order.getRealTotalMoney()), "aliSuperMarketAgainNotify.do");
            return aliPay.appPay(wxOrderVO);
        } else {
            return new AjaxResult().addError("支付失败");
        }
    }

    /**
     * 创建订单
     *
     * @param orderVO
     */
    @Transactional
    public AjaxResult createOrder(HttpServletRequest request,OrderVO orderVO) {
        //订单价格
        BigDecimal price = new BigDecimal("0");
        //该完整订单的订单号:
        String orderNum = "Y"+CommonUtil.getOutTradeNo();
        //运费
        BigDecimal freight = new BigDecimal("5");
        //多订单
        if (orderVO.getShopCarIds() != null && orderVO.getShopCarIds().size() > 0) {
            freight = freight.divide(new BigDecimal(orderVO.getShopCarIds().size()), 2, RoundingMode.HALF_UP);
            for (Integer shopCarId : orderVO.getShopCarIds()) {
                BigDecimal thisOrderPrice = this.makeOrder(shopCarId, orderVO, freight, orderNum);
                price = price.add(thisOrderPrice);
            }
        } else {//单订单
            price = this.makeOrder(null,orderVO,freight,orderNum);
        }
        if (orderVO.getShopCarIds() != null && orderVO.getShopCarIds().size() > 0) {
            //删除购物车信息
            for (Integer shopCarId : orderVO.getShopCarIds()) {
                shopCarService.deleteByPrimaryKey(shopCarId);
            }
        }
        //微信支付
        if (orderVO.getPayType() == 2) {
            WxOrderVO wxOrderVO = new WxOrderVO("圆梦超市订单", "1", orderNum, price.multiply(new BigDecimal("100")).intValue()+"", "superMarketNotify.do");
            return wxPay.appPay(request, wxOrderVO);
        } else if (orderVO.getPayType() == 1) {
            WxOrderVO wxOrderVO = new WxOrderVO("圆梦超市订单", "1", orderNum, price, "aliSuperMarketNotify.do");
            return aliPay.appPay(wxOrderVO);
        } else {
            return new AjaxResult().addError("支付失败");
        }
    }


    /**
     *
     * @param shopCarId
     * @param orderVO
     * @param freight
     * @param orderNum
     * @return 订单价格
     */
    private BigDecimal makeOrder(Integer shopCarId, OrderVO orderVO, BigDecimal freight, String orderNum) {
        ShopCar shopCar;
        Integer goodsId;
        Integer goodsNumber;
        if (shopCarId == null) {
            goodsId = orderVO.getGoodsId();
            goodsNumber = orderVO.getNum();
        } else {
            shopCar = shopCarService.selectByPrimaryKey(shopCarId);
            goodsId = shopCar.getGoodsId();
            goodsNumber = shopCar.getGoodsNumber();
        }
        Goods goods = goodsService.selectByPrimaryKey(goodsId);

        //减库存
        goods.setGoodsStock(goods.getGoodsStock()-goodsNumber);
        goodsMapper.updateByPrimaryKeySelective(goods);

        double goodsMarketPrice = goods.getGoodsMarketPrice();
        //订单号
        String tradeNo = CommonUtil.getOutTradeNo();
        Order order = new Order();
        order.setOrderOn(tradeNo);
        order.setUserId(orderVO.getUserId());
        order.setGoodsId(goodsId);
        order.setGoodsNumber(goodsNumber);
        order.setGoodsMoney(goodsMarketPrice);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsImg(goods.getGoodsPicFour());
        order.setDeliverMoney(freight.doubleValue());
        order.setTotalMoney(goodsMarketPrice * goodsNumber + order.getDeliverMoney());
        order.setRealTotalMoney(goodsMarketPrice * goodsNumber + order.getDeliverMoney());
        //未支付
        order.setOrderStatus(-2);
        order.setPayType(orderVO.getPayType());
        order.setUserAddressId(orderVO.getUserAddressId());
        order.setOrderRemarks(orderVO.getOrderRemarks());
        order.setOrderTime(new Date());
        order.setOrderNum(orderNum);
        orderMapper.insertSelective(order);
        log.info("用户下单了，订单号为：{}", order.getOrderNum());
        return BigDecimal.valueOf(order.getRealTotalMoney());
    }

    /**
     * 回调改变订单状态
     * @param orderNum
     */
    @Transactional
    public void notifyOrderStatus(String orderNum) {
        List<Order> orderList = orderMapper.selectByOrderNum(orderNum);
        if(orderList==null) return;
        for (Order order : orderList) {
            order.setOrderStatus(0);
            order.setPayTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
            log.info("修改自订单号为{}的订单状态为已支付", order.getOrderOn());
        }
    }


    /**
     * 获取订单是否支付完成
     * @param orderNum
     * @return  false代表未完成需要重新回调 true代表完成不需要回调
     */
    public boolean getIsFinish(String orderNum) {
        List<Order> orderList = orderMapper.selectByOrderNum(orderNum);
        for (Order order : orderList) {
            if (order.getOrderStatus() == -2) {
                return false;
            }
        }
        return true;
    }



    /**
     * 定时取消订单
     */
    public void timingCancelOrder() {
        orderMapper.cancelOrder();
    }

    /**
     * 定时确认收获
     */
    public void timingConfirmOrder() {
        //查询所有待收货订单
        List<Order> orderList = orderMapper.selectByStatus(1);
        for (Order order : orderList) {
            if (order.getOrderTime().before(DateUtil.offsetDay(new Date(), -7))) {
                Goods goods = goodsService.selectByPrimaryKey(order.getGoodsId());
                //加销量
                goods.setGoodsSales(order.getGoodsNumber() + goods.getGoodsSales());
                goodsService.updateById(goods);
                order.setOrderStatus(4);
                orderMapper.updateByPrimaryKeySelective(order);
            }
        }
    }

    /**
     * 根据订单状态查询数量
     * @param type -4 全部 -2待支付 0待发货 1待收货 4订单完成
     * @return
     */
    public int selectCountByType(Integer type,Integer userId) {
        return orderMapper.countByStatus(type, userId);
    }

    public Order getOrderStatusByOrderOn(String orderOn) {
        return orderMapper.selectByOrderOn(orderOn);
    }

    /**
     * 单个订单改变状态
     * @param orderOn 子订单号
     */
    public void notifyOrderStatusByOrderOn(String orderOn) {
        Order order = orderMapper.selectByOrderOn(orderOn);
        order.setPayTime(new Date());
        order.setPayType(2);
        order.setOrderStatus(0);
        orderMapper.updateByPrimaryKeySelective(order);
        log.info("重新下单订单更改{}的订单状态为已支付",orderOn);
    }
}
